(function () {
    function debounce(fn, wait) {
        var timer = null;
        return function (e) {
            if (timer !== null) {
                clearTimeout(timer);
            }
            timer = setTimeout(function () {
                fn.call(this, e);
            }, wait);
        };
    }

    function throttle(func, wait) {
        
        let old = 0;
        return function () {
            
            let now = new Date().valueOf();
            if (now - old > wait) {
                
                func.apply(this, arguments);

                old = now;
            }
        };
    }

    
    function editBlock(URL, settings, callback) {
        $.ajax({
            url: URL,
            type: "post",
            dataType: "json",
            headers: {
                "Content-Type": "application/json;charset=UTF-8"
            },
            data: JSON.stringify(settings),
            complete: function (e) {
                if (e.status === 200) {
                    callback && callback.call(this, e.responseText);
                } else {
                    alert("更新积木块失败");
                }
            }
        });
    }
    const throttleEditBlock = throttle(editBlock, 500);

    function message(e) {
    
        var messageData = JSON.parse(JSON.stringify(e.data));

        if (!messageData || !messageData.type) {
            return false;
        }
        if( messageData.type != "position" && $('.plugin-container-tabbar').html()){
            $('.plugin-container-tabbar').html("")
        }
        // console.log("接受数据", messageData, e);
        let blockNode = $("#block-section-" + messageData.id);

        let mainContent = $("#MainContent");

        let _addBtn = $("#oemsaas-add-btn");

        let _body = $("html,body");

        let addHtml = `<div class="oemsaas-add" id='oemsaas-add-btn'>点击右侧卡片添加到这里</div>`;

        
        
        
        

        
        
        
        
        
        
        
        
        
        
        
        

        
        function hrefRedirect(node) {
            node.find("a").click(function (e) {
                e.preventDefault();
                moi.href($(this).attr("href"));
            });
        }

        
        function positionCurrent(id, isLazy) {
            
            _addBtn && _addBtn.remove();

            
            if (document.referrer === "" || document.referrer.indexOf(location.host + "/admin") > -1 || moi.getUrlParam("theme_id")) {
                $(".back-box").hide();
            }

            
            if (window.productSize) {
                window.productSize && productSize($(".product_img"));
            }

            
            positionNode = $(`#block-section-${id}`);

            if (messageData.block_type === "header" || messageData.block_type === "footer") {
                positionNode = $(`#card-${messageData.block_type}`);
            }

            
            



            
            const oldBlockId = sessionStorage.getItem("blockId");
            if (oldBlockId && Number(oldBlockId) === id) {
                return false;
            }

            sessionStorage.setItem("blockId", messageData.id);

            if (id && positionNode.length) {
                animateScrollTop(positionNode);
            }
        }

        
        function animateScrollTop(node) {
            const nodeTop = node.offset().top - 20;

            _body.stop().animate({ scrollTop: nodeTop }, 800, "linear", function () {
                
                if (_body.scrollTop() < nodeTop) {
                    _body.stop().animate({ scrollTop: node.offset().top }, 400, "linear");
                }
            });
        }

        
        function addDelNode() {
            if (!_addBtn.length) {
                mainContent.append(addHtml);
                _addBtn = $("#oemsaas-add-btn");
                animateScrollTop(_addBtn);
                sessionStorage.removeItem("blockId"); 
            }
        }

        if (messageData.id && messageData.settings) {
            
            messageData.settings["block_id"] = messageData.id || new Date().getTime();
            
            messageData.settings["page_id"] = moi.getPageStorage("page_id") || messageData.settings.page_id;

            
            messageData.settings["params"] = moi.getPageStorage("messageParams");

            
            if (themeConfig) {
                messageData.settings["theme_config"] = themeConfig;
            }
            
            messageData.settings["type"] = messageData.block_type;

            
            messageData.settings["router"] = window.oemcart_current_router || "";
            messageData.settings["router_handle"] = window.oemcart_current_route_handle || "";
        }

        switch (messageData.type) {
            
            case "global":
                location.reload();
                break;
            
            case "sort":
                
                
                
                
                location.reload();
                break;
            
            case "block":
                
                if (messageData.settings.settings.refresh) {
                    location.reload();
                    return;
                }

                let themeId = moi.getUrlParam("theme_id");
                let themeIdParms = themeId ? `?theme_id=${themeId}&page_ca=${window.oemcart_page_ca || ""}` : "";
                var URL = `/block/type/${messageData.block_type}${themeIdParms}`;

                throttleEditBlock(URL, messageData.settings, function (html) {
                    if (messageData.block_type === "header" || messageData.block_type === "footer") {
                        const node = $(`#card-${messageData.block_type}`);
                        node.html(html);
                        positionCurrent(messageData.id, false);
                        
                        
                        moi.onEvent("updateBlock", { messageData });
                        return;
                    }
                    blockNode.html(html);
                    
                    moi.onEvent("updateBlock", { messageData });
                    
                    
                    positionCurrent(messageData.id, true);
                });
                break;
            
            case "position":
                messageData.id ? positionCurrent(messageData.id) : addDelNode();
                moi.onEvent("positionBlock", { messageData });
                break;
            
            case "del":
                $("#block-section-" + messageData.delId).remove();
                addDelNode();
                moi.onEvent("delBlock", { messageData });
                break;
            
            case "display":
                if (messageData.settings.display) {
                    blockNode.hide();
                } else {
                    blockNode.show();
                }
                break;
            
            case "add": {
                

                let themeId = moi.getUrlParam("theme_id");
                let themeIdParms = themeId ? `?theme_id=${themeId}&page_ca=${window.oemcart_page_ca || ""}` : "";
                var URL = `/block/type/${messageData.block_type}${themeIdParms}`;
                throttleEditBlock(URL, messageData.settings, function (html) {
                    let newblockHtml = `<div id="block-section-${messageData.id}" data-section-type="${messageData.block_type}" data-section-id="${messageData.id}">${html}</div>`;
                    mainContent.append(newblockHtml);
                    positionCurrent(messageData.id, true);
                    
                    
                    
                    moi.onEvent("addBlock", { messageData });
                });
                break;
            }
        }
    }

    
    window.onmessage = message;

    
    window.parent.postMessage(
        {
            type: "load",
            current_router: oemcart_current_router || "",
            current_router_handle: window.oemcart_current_route_handle || "",
            href: decodeURIComponent(window.location.href)
        },
        "*"
    );

    console.log("加载成功通知", {
        type: "load",
            current_router: oemcart_current_router || "",
            current_router_handle: window.oemcart_current_route_handle || "",
            href: decodeURIComponent(window.location.href)
    });

    
    window.addEventListener("beforeunload", function (e) {
        console.log("卸载通知", {
            type: "unload",
            current_router: oemcart_current_router,
            current_router_handle: window.oemcart_current_route_handle || "",
            href: decodeURIComponent(window.location.href)
        });
        sessionStorage.removeItem("blockId");
        window.parent.postMessage(
            {
                type: "unload",
                current_router: oemcart_current_router,
                current_router_handle: window.oemcart_current_route_handle || "",
                href: decodeURIComponent(window.location.href)
            },
            "*"
        );
        return false;
    });
})();

